// Copyright 2011 Bryan McKelvey, MIT License

/**
 * @fileoverview The Options singleton and the methods available to it
 * @author bryan.mckelvey@gmail.com (McKelvey Bryan)
 */

/**
 * This class interacts with the options page, placing settings values into a form and saving them
 * at user request
 * @constructor
 */
var Options = (function() {
  /**
   * The ID of the form
   * @const
   * @type {string}
   */
  var FORM_ID = "options";
  
  /**
   * The text of an alert to the user when settings are saved
   * @type {string}
   * @const
   */
  var SAVE_ALERT = "Settings saved!";
  
  /** A reference to the background page */
  var bg = chrome.extension.getBackgroundPage();
  
  /** A reference to the main form */
  var form = document.getElementById(FORM_ID);
  console.log(form);
  
  /** A reference to input elements in the main form */
  var inputs = document.getElementsByTagName("input", form);
  console.log(inputs);
  
  return {
    /** Loads the current settings into the form on the options page */
    load: function() {
      var settings = bg.Settings.all();
      
      for (var key in settings) {
        var input = document.getElementById(key, form);
        if (input) {
          switch (input.type) {
            case "checkbox":
              input.checked = settings[key];
              break;
            default:
              input.value = settings[key];
              break;
          }
        }
      }
    },
    
    /** Saves the settings based on changes made on the options page */
    save: function() {
      for (var i = 0; i < inputs.length; i++) {
        var input = inputs[i];
        var value;
        
        switch (input.type) {
          case "checkbox":
            value = input.checked;
            break;
          default:
            value = input.value;
            break;
        }
        
        console.log("ID: " + input.id + ", value: " + value);
        bg.Settings.set(input.id, value);
      }
      alert(SAVE_ALERT);
    }
  }
})();

Options.load();